(function() {
    'use strict';

    angular.module("weApp.directives", [])

            .directive('myfocus', ['$timeout', function($timeout) {
                    return {
                        link: function(scope, element) {
                            $timeout(function() {
                                element[0].focus();
                            }, 300);
                        }
                    };
                }])

            .directive("zhxPageLoading", ['$compile', function($compile) {
                    return {
                        restrict: "E",
                        replace: true,
                        template: "<div id='zhx-page-loading'></div>",
                        link: function(scope, element) {
                            var spinner = $compile("<ion-spinner icon='android'></ion-spinner>")(scope);
                            element.append(spinner);
                        }
                    }
                }])

            .directive("zhxPopTip", ['$timeout', function($timeout) {
                    return {
                        restrict: "E",
                        replace: true,
                        scope: {
                            showTip: '=',
                            content: '=',
                            time: '='
                        },
                        link: function(scope, element, attrs) {

                            scope.$watch('showTip', function(nv, ov) {
                                if (nv) {
                                    $timeout(function() {
                                        scope.showTip = !scope.showTip;
                                    }, scope.time || 1200);
                                }
                            });

                        },
                        template: '<div class="zhx-pop-tip-container" ng-class="{ zhxPopTipActive : showTip }">' +
                                '<div class="zhx-pop-tip">' +
                                '<div class="zhx-pop-content">{{ content }}</div>' +
                                '</div>' +
                                '</div>'

                    }
                }])

            .directive("lineMap", ['$rootScope', '$state', '$timeout', '$http', '$ionicLoading', function($rootScope, $state, $timeout, $http, $ionicLoading) {
                    return {
                        restrict: "E",
                        scope: {
                            lineData: '=',
                            favors: '=',
                            getLineData: '&'
                        },
                        replace: true,
                        template: "<div id='line-map' ng-style='{ width: stationLineWidth , height: stationLineHeight, background: stationLineColor }'>" +
                                //循环所有车辆实时位置
                                "<div class='we-font we-icon-bus1 line-map-bus' " +
                                " ng-repeat='bus in lineBus track by bus.busNum' " +
                                " ng-if='!busLeftArr[$index].repeat' " +
                                " ng-style='{ left: busLeftArr[$index].busPos }' " +
                                " ng-class='{ nearByBus : nearbyBusNum == bus.busNum && !noBus }'>" +
                                // "<label class='bus-num' ng-if='nearbyBusNum == bus.busNum && !noBus'>{{nearbyBusNum}}</label>" +
                                "<div class='topbusNum' ng-if='nearbyBusNum == bus.busNum && !noBus'>{{ bus.busNum }}</div>" +
                                "<span ng-if='busLeftArr[$index].repeatNum > 0' ng-class='{ nearByBusTip: busLeftArr[$index].repeatBusNum.indexOf( nearbyBusNum ) >= 0 }'>{{ busLeftArr[$index].repeatNum + 1 }}</span>" +
                                "</div>" +
                                //循环出直线图站点圆点
                                "<div class='line-map-station-dot' " +
                                " ng-style='{ left : $index * stationDistance + 25, width: stationLineHeight - 2, height: stationLineHeight - 2 }' " +
                                " ng-repeat='s in lineData track by s.lineStationId'></div>" +
                                //当前站点位置标记
                                "<div ng-if='isNowStation' class='line-map-pos' ng-style='{left : nowStationLeft }'></div>" +
                                // 循环出直线图所有站点名称
                                "<div bindonce class='line-map-station' " +
                                " ng-style='{ left : $index * stationDistance + 18, height: maxTextLen * 19.5 + 40 }' " +
                                " ng-repeat='s in lineData track by s.lineStationId' ng-click='showStationPrec({{s}})'> " +
                                " <span ng-if='favors.indexOf( s.lineStationId ) == -1' bo-text='$index + 1'></span> " +
                                " <span ng-if='favors.indexOf( s.lineStationId ) != -1' class='we-font we-icon-favorfill favor-active'></span>" +
                                " <span class='station-name' ng-class='{ nowStation: isNowStation == s.lineStationId }' ng-style='{ fontSize : s.autoSmallFont }' bo-text='s.stationName'></span>" +
                                "</div>" +
                                "</div>",
                        controller: ["$scope", "$ionicScrollDelegate", "localStorageService", function($scope, $ionicScrollDelegate, localStorageService) {

                                //直线图上点击任意站点查询预测时间
                                $scope.showStationPrec = function(station) {
                                    //防止多次点击重复获取数据
                                    if ($scope.isNowStation != station.lineStationId) {

                                        /**
                                         * 每当切换站点都应该更新session中的当前限流站点信息，保证收藏站点的正确
                                         */
                                        sessionStorage.setItem("clickLine", JSON.stringify(station));
                                        $scope.getLineData();

                                        $scope.clickStationName = station.stationName;
                                        $scope.isNowStation = station.lineStationId;
                                        $scope.nowStationLeft = (parseInt(station.seq) - 1) * $scope.stationDistance + 21;
                                        $scope.nowStationObj = station;
                                        $scope.searchNearbyBus(station);
                                    }
                                };

                                //画面滚动至当前站点
                                $scope.scrollTo = function(leftPos) {
                                    $ionicScrollDelegate.$getByHandle("lineMap").scrollTo(leftPos, 0, true);
                                }

                            }],
                        link: function(scope, element, attrs) {

                            //监测线路基础数据读取情况
                            scope.lineDataWatcher = scope.$watch('lineData', function(nv, ov) {
                                if (nv !== ov && nv.length) {
                                    //延迟事件是为了保证更多低端机型在转场动画后再渲染直线图
                                    $timeout(function() {
                                        scope.initMap();
                                        // console.log("line107: 初始化直线图");
                                    }, 300);
                                }
                            });

                            //绘制直线图
                            scope.initMap = function() {

                                //当前线路所有的车的数组对象
                                scope.lineBus = [];
                                //该数组存入的为当前线路所有车辆在直线图中相对左侧的位置< 也就是车辆的实时位置 >
                                scope.busLeftArr = [];
                                scope.nowStationObj = null;
                                scope.noBus = false;

                                scope.isNowStation = null;

                                scope.isAutoRefresh = true;
                                scope.autoRefreshTime = 6000;

                                scope.busInterval = null;

                                //每站在页面上的间距（PX像素）
                                scope.stationDistance = 50;
                                //直线图高度
                                scope.stationLineHeight = 8;
                                //直线图背景色
                                scope.stationLineColor = "#0d9d57";
                                //直线图上一共多少站
                                scope.stationNum = scope.lineData.length;
                                //计算整体直线图需要的长度，长度根据线路多少和间距来确定
                                scope.stationLineWidth = scope.stationNum * scope.stationDistance;
                                //当前线路下最长站名一共几个字，根据这个来计算站名高度
                                scope.maxTextLen = 0;

                                var nowStationLine = JSON.parse(sessionStorage.getItem('clickLine'));

                                /**
                                 * 设置线路上的当前站点显示的临时方法
                                 */
                                var setNowStationPos = function() {
                                    //设置第几站为当前站
                                    scope.isNowStation = line.lineStationId;
                                    //设置当前站
                                    scope.nowStationObj = line;
                                    //页面打开时自动滚动到当前站点（距离屏幕四站）
                                    //位置刚好在中间偏右，方便查看离当前站点最近的几辆车
                                    scope.scrollTo((i - 4) * scope.stationDistance);
                                    scope.nowStationLeft = i * scope.stationDistance + 21;
                                };

                                var stationTextLenArr = [];

                                for (var i = 0; i < scope.lineData.length; i++) {
                                    var line = scope.lineData[i];

                                    stationTextLenArr.push(line.stationName.length);

                                    if (line.stationName.length > 10) {
                                        scope.lineData[i].autoSmallFont = '.95em';
                                    }

                                    /**
                                     * 设置线路上的当前站点显示
                                     * @param  {[type]} line.lineStationId [description]
                                     * @return {[type]}                    [description]
                                     */
                                    if (line.lineStationId == nowStationLine.lineStationId) {
                                        setNowStationPos();
                                    } else {
                                        /**
                                         * 如果用户使用了换向功能，目前无法通过独立ID来设置换向后的当前站点，只能以站点名称来判断。
                                         * @type {[type]}
                                         */
                                        if (line.stationName == nowStationLine.stationName) {
                                            setNowStationPos();
                                            /**
                                             * 每当切换站点都应该更新session中的当前限流站点信息，保证收藏站点的正确
                                             */
                                            sessionStorage.setItem("clickLine", JSON.stringify(line));
                                            scope.getLineData();

                                        }
                                    }
                                }

                                /**
                                 * 对所有站名长度进行排序
                                 */
                                stationTextLenArr.sort(scope.sortArr);
                                scope.maxTextLen = stationTextLenArr[0];

                                /**
                                 * 如果用户进入线路预测页面但没有查询到当前站点，则需要进行一些容错处理
                                 * @param  {[type]} scope.nowStationObj [description]
                                 * @return {[type]}                     [description]
                                 */
                                if (scope.nowStationObj == null) {
                                    for (var i = 0; i < scope.lineData.length; i++) {
                                        var line = scope.lineData[i];
                                        if (line.seq == nowStationLine.seq) {
                                            setNowStationPos();
                                            /**
                                             * 每当切换站点都应该更新session中的当前限流站点信息，保证收藏站点的正确
                                             */
                                            sessionStorage.setItem("clickLine", JSON.stringify(line));
                                            scope.getLineData();

                                        }
                                    }
                                }
                                if (scope.nowStationObj == null) {
                                    console.warn("line197: 该线路下没有找到对应站点.");
                                    //如果在该线路下获取不到对应站点，则将该线路第一站点设置为当前站点；
                                    scope.nowStationObj = scope.lineData[0];
                                    //并弹出提示
                                    scope.$parent.lineData.lineStationId = "zhx-no-bus";
                                    scope.$parent.lineData.tipShown = true;
                                    scope.$parent.lineData.tipContent = "没有找到定位的站点/相应序号.";
                                    scope.$parent.lineData.tipTime = 2000;
                                    scope.scrollTo(0);
                                    $ionicLoading.hide();
                                    // $state.go( $rootScope.prevState );
                                    // return;
                                }

                                //绘制线路上存在的公交实时位置
                                scope.initStationBus();

                            };

                            /**
                             * 目前接收控制器传来的事件，主要刷新车辆和单车预测信息
                             * @param  {[type]} event                            [description]
                             * @return {[type]}                                  [description]
                             */
                            scope.$on("refreshStationBus", function(event, data) {
                                scope.initStationBus();
                            });

                            //读取
                            scope.initStationBus = function() {
                                var nowLineData = JSON.parse(sessionStorage.getItem('clickLine'));

                                var req = {
                                    method: 'post',
                                    url: $rootScope.rootLocation + '/line/bus/positions',
                                    data: {
                                        "lineId": nowLineData.lineId,
                                        "lineType": nowLineData.lineType.toString(),
                                        "cityCode": $rootScope.cityCode
                                    }
                                };

                                $http(req)
                                        .then(function(result) {

                                            if (result.data.head.success == "true") {

                                                if (result.data.data.busInfos.length) {

                                                    // console.log(  result.data.data.busInfos );
                                                    //
                                                    scope.lineBus = result.data.data.busInfos;
                                                    $rootScope.busNums = result.data.data.busInfos;
                                                    var busPosArrTpl = [];

                                                    for (var i = 0; i < scope.lineBus.length; i++) {

                                                        var bus = scope.lineBus[i];

                                                        //计算每一个车辆在直线图上的实时位置
                                                        var busPos = (scope.stationDistance * parseFloat(bus.relativePosition)) + ((bus.seq - 1) * scope.stationDistance) + 18;


                                                        var req = {
                                                            busPos: busPos,
                                                            busNum: bus.busNum,
                                                            repeat: false,
                                                            repeatNum: 0,
                                                            repeatBusNum: []
                                                        }

                                                        busPosArrTpl.push(req);

                                                        /**
                                                         * 如果当前车辆与上一辆位置发生重叠，则将当前车辆隐藏，并设置上一辆车显示TIP，表示同一个图标下有几辆车重叠
                                                         */
                                                        //当然要从第二辆车开始循环
                                                        if (busPosArrTpl.length > 1) {
                                                            //如果当前车辆与上一辆车的位置距离 < 16像素，则因此当前车辆，设置上一辆车显示+1
                                                            if (busPos - busPosArrTpl[i - 1].busPos < 16) {
                                                                busPosArrTpl[i].repeat = true;
                                                                busPosArrTpl[i - 1].repeatBusNum.push(busPosArrTpl[i].busNum)
                                                                busPosArrTpl[i - 1].repeatNum += 1;
                                                            }
                                                        }

                                                    }
                                                    ;

                                                    /**
                                                     * 对临时数组进行倒序循环，累加所有重叠车辆。
                                                     */
                                                    for (var j = busPosArrTpl.length - 1; j >= 0; j--) {
                                                        var sbus = busPosArrTpl[j];
                                                        if (sbus.repeat) {
                                                            busPosArrTpl[j - 1].repeatNum += sbus.repeatNum;
                                                            busPosArrTpl[j - 1].repeatBusNum = $.merge(busPosArrTpl[j - 1].repeatBusNum, sbus.repeatBusNum);
                                                            sbus.repeatNum = 0;
                                                            sbus.repeatBusNum = [];
                                                        }
                                                    }

                                                    // console.log( busPosArrTpl );
                                                    //更新车辆实时位置
                                                    scope.busLeftArr = busPosArrTpl;
                                                    // console.log( scope.busLeftArr );
                                                    //
                                                    //查找最近一辆车
                                                    scope.searchNearbyBus(scope.nowStationObj);

                                                }


                                            } else {
                                                console.warn("line313: 获取车辆信息失败");
                                                scope.$parent.lineData.nobus = scope.noBus = true;
                                                $ionicLoading.hide();
                                            }


                                        }, function() {
                                            console.warn('line321: 获取车辆信息出错，请检查代码.');
                                            $ionicLoading.hide();
                                        })


                            };

                            /**
                             * 寻找距离当前站点最近的一辆车
                             * @param  {[type]} nowStationObject [description]
                             * @return {[type]}                  [description]
                             */
                            scope.searchNearbyBus = function(nowStationObject) {


                                var tplBusArr = [];

                                var filterArr = scope.filterObject('seq', scope.lineBus, parseInt(nowStationObject.seq) - 1);

                                //直接取临时数组中的最后一辆车就是最近的一辆
                                //因为车辆不论上下行，都是从左至右排列
                                var nearBus = filterArr.splice(filterArr.length - 1, 1);

                                if (!nearBus.length) {
                                    //这里需要设置无最近车辆的提示
                                    scope.$parent.lineData.nobus = scope.noBus = true;
                                    $ionicLoading.hide();
                                    return;
                                } else {
                                    scope.$parent.lineData.nobus = scope.noBus = false;
                                }

                                //循环后设置页面最近一辆车的样式
                                for (var j = 0; j < scope.lineBus.length; j++) {
                                    if (nearBus[0].busNum == scope.lineBus[j].busNum) {
                                        scope.nearbyBusNum = nearBus[0].busNum;
                                        // console.log( scope.nearbyBusNum );
                                        break;
                                    }

                                }
                                ;

                                //查询最近一辆车的实时预测数据
                                scope.loadNearByBusPrec(nearBus[0]);

                            };

                            /**
                             * 查询距离当前站点最近一辆车的实时数据
                             * @param  {[type]} nearByBus [description]
                             * @return {[type]}           [description]
                             */
                            scope.loadNearByBusPrec = function(nearByBus) {

                                /**
                                 * 请求数据的参数
                                 * @type {Object}
                                 */
                                var req = {
                                    method: 'post',
                                    url: $rootScope.rootLocation + '/line/bus/predict',
                                    data: {
                                        "lineId": scope.nowStationObj.lineId,
                                        "lineStationId": scope.nowStationObj.lineStationId,
                                        "busNum": nearByBus.busNum
                                    }
                                };

                                $http(req)
                                        .then(function(result) {

                                            if (result.data.head.success == "true") {
                                                scope.$parent.lineData.busInfo = result.data.data.busInfo;
                                                scope.$parent.lineData.busInfo.stationName = scope.clickStationName;
                                            } else {
                                                console.warn("line399: 获取最近一辆车预测信息失败");
                                            }

                                            $ionicLoading.hide();

                                        }, function() {
                                            console.warn('line407: 获取最近一辆车预测信息失败，请检查代码.');
                                            $ionicLoading.hide();
                                        })

                            };


                            // scope.sortArrObject = function(sortBy, list) {
                            // 	return list.sort(function(a, b) {
                            // 	    // 降序，若需要升序则互换两者位置
                            // 	    if( !$.isNumeric( a[sortBy] ) ){
                            // 	    	return parseFloat( b[sortBy] ) - parseFloat( a[sortBy] );
                            // 	    } else {
                            // 	    	return b[sortBy] - a[sortBy];
                            // 	    }
                            // 	});
                            // };
                            //
                            scope.sortArr = function(a, b) {
                                if (a < b) {
                                    return 1; // a排在b的后面
                                } else if (a > b) {
                                    return -1; // a排在b的前面
                                } else {
                                    return 0; // a 和 b 保持位置不变
                                }
                            }


                            /**
                             * 过滤出数组中的某个属性小于等于某值的数组对象
                             * 并返回符合条件的新数组对象
                             * @param  {[type]} prop [description]
                             * @param  {[type]} arr  [description]
                             * @param  {[type]} num  [description]
                             * @return {[type]}      [description]
                             */
                            scope.filterObject = function(prop, arr, num) {
                                var tplArr = [];
                                for (var i = 0; i < arr.length; i++) {
                                    if ($.isNumeric(arr[i][prop])) {
                                        var substract = num - arr[i][prop];
                                        if (substract >= 0)
                                            tplArr.push(arr[i]);
                                    } else {
                                        var substract = num - parseFloat(arr[i][prop]);
                                        if (substract >= 0)
                                            tplArr.push(arr[i]);
                                    }
                                }
                                return tplArr;
                            };

                        }

                    }
                }])

})();